"""
*** 利用画布，分图绘制柱状图 ***
"""

import matplotlib.pyplot as plt
import numpy as np

# 假设这是你的数据点，横坐标使用月份名称
years = [
    "一月",
    "二月",
    "三月",
    "四月",
    "五月",
    "六月",
    "七月",
    "八月",
    "九月",
    "十月",
    "十一月",
    "十二月",
]
base_data = {
    "公安": [509, 361, 622, 579, 514, 437, 463, 558],  # 公安
    "信访": [96, 71, 124, 141, 128, 67, 122, 102],  # 信访
    "劳动仲裁": [56, 44, 46, 50, 50, 38, 62, 55],  # 劳动仲裁
    "劳动监察": [246, 186, 158, 116, 150, 149, 173, 166],  # 劳动监察
    "法院": [348, 262, 450, 348, 479, 582, 436, 443],  # 法院
}
labels = list(base_data.keys())
y = list(base_data.values())

# colors = ["red", "blue", "green", "black", "purple"]
colors = ["#4f80bd", "#c0504d", "#9bbb59", "#8064a2", "#4bacc6"]
months = years[: len(y[0])]

# 创建一个包含3行2列子图的画布
fig, axs = plt.subplots(3, 2, layout="constrained", figsize=(10, 7))

for i in range(len(labels)):
    # plt.subplot(3, 2, i + 1)
    # plt.bar(months, y[i], label=labels[i], color=colors[i])
    row = i // 2  # 计算子图所在的行
    col = i % 2  # 计算子图所在的列
    v_bar = axs[row, col].bar(months, y[i], label=labels[i], color=colors[i])
    axs[row, col].legend()
    # axs[row, col].set_xlabel("月份")
    axs[row, col].set_ylabel("数量")
    axs[row, col].set_ylim(0, max(y[i]) + 100)
    axs[row, col].grid(True)
    # 绘制折线
    axs[row, col].plot(months, y[i], color=colors[i])
    # axs[row, col].set_title(labels[i])

    # 在每个柱子上显示数值
    # 第一种方法
    # for j, v in enumerate(y[i]):
    #     # 在条形上方添加文本
    #     axs[row, col].text(j, v + 0.5, str(v), ha="center", va="bottom")
    # 第二种方法
    axs[row, col].bar_label(v_bar, label_type="edge")

# axs[2, 1].clear()  # 清除最后一个子图，因为我们不需要它
# axs[2, 1].set_axis_off()
# # axs[2, 1].set_xticks([])
# # axs[2, 1].set_yticks([])
# # axs[2, 1].set_title("")

# axs[2, 1]  # 最后一个子图，画饼图

sum_y = [sum(x) for x in y]
paches, texts, autotexts = axs[2, 1].pie(
    sum_y,
    labels=labels,
    colors=colors,
    autopct="%1.0f%%",
    startangle=90,
    # counterclock=True,
    labeldistance=1.2,
    explode=[0.05, 0, 0, 0, 0.05],  # 某个扇区离开圆心的距离，用于突出显示某个扇区
    # frame=True,
    # center=(1, 1),
)

# 可以进一步自定义文本和扇区
for text in texts:
    text.set_color("black")  # 将文本颜色设置为黑色
    text.set_fontsize(10)  # 设置文本大小

for text in autotexts:
    text.set_color("white")  # 将自动生成的文本颜色设置为白色
    text.set_fontsize(8)  # 设置文本大小

for pache in paches:
    pache.set_edgecolor("black")  # 将扇区边缘颜色设置为黑色

# 为每个扇区添加连接线
for i, p in enumerate(paches):
    ang = (p.theta2 - p.theta1) / 2.0 + p.theta1
    y = np.sin(np.deg2rad(ang))
    x = np.cos(np.deg2rad(ang))
    horizontalalignment = {-1: "right", 1: "left"}[int(np.sign(x))]
    connectionstyle = f"angle,angleA=0,angleB={ang},rad=0"

    # 连接线的起点是扇区的中心
    axs[2, 1].annotate(
        "",
        xy=(x, y),  # 起点
        xytext=(1.35 * np.sign(x), 1.35 * y),  # 终点
        arrowprops=dict(
            arrowstyle="-|>",
            connectionstyle=connectionstyle,
            color="darkred",
            alpha=0.2,
        ),  # 连接线属性
        # horizontalalignment=horizontalalignment,
    )


# 设置中文用楷体
plt.rcParams["font.sans-serif"] = ["SimHei"]
plt.rcParams["axes.unicode_minus"] = False  # 解决负号'-'显示为方块的问题

# 添加总标题
plt.suptitle(f"1-{len(months)}月主要部门矛盾纠纷排查情况", fontsize=24)
# 显示图形
plt.show()
